<?php

namespace Xin\Wechat;

use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\OfficialAccount\Application;
use Xin\Wechat\Exceptions\WechatNotConfigureException;

trait HasOfficialAccount
{
	/**
	 * 获取默认的公众号
	 * @return string
	 */
	public function getDefaultOfficialAccount()
	{
		return $this->getConfig('defaults.official_account');
	}

	/**
	 * 获取公众号配置
	 * @param string $name
	 * @return array
	 */
	public function getOfficialAccountConfig(string $name)
	{
		return $this->getConfig("official_accounts." . $name, []);
	}

	/**
	 * 是否有公众号配置
	 * @param string $name
	 * @return bool
	 */
	public function hasOfficialAccountConfig($name)
	{
		return $this->hasConfig("official_accounts.{$name}");
	}

	/**
	 * 构造公众号实例
	 * @param array $config
	 * @param array $options
	 * @return Application
	 * @throws InvalidArgumentException
	 */
	public function makeOfficialAccount($config, $options, string $providerName = null)
	{
		if (empty($config)) {
			throw new WechatNotConfigureException("wechat config 'official_accounts.{$providerName}' not defined.");
		}

		$config = $this->checkApplicationConfig($config);

		return $this->initApplication(
			new Application($config),
			$options
		);
	}
}
